package com.supconit.kqfx.web.util;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by JNJ on 2018/5/24.
 * java从网络中下载图片到本地
 */
public class ImageDownload {

    public static void main(String[] args) {
        String urlStr = "http://img.zcool.cn/community/01b5ff5621157032f87557019c89de.jpg@2o.jpg";
        try {
            URL url = new URL(urlStr);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String dirName = "E:/" + "2018/" + "05/" + "28/";
            //创建文件
            String imageName = dirName + "YJ_02-车牌-日期-随机数-" + "test.jpg";
            File dir = new File(dirName);
            boolean canCreateImage = true;
            //判断目录是否存在
            if (!dir.exists()) {
                //创建目录
                if (!dirName.endsWith(File.separator)) {
                    dirName = dirName + File.separator;
                }
                //创建目录
                dir.mkdirs();
                canCreateImage = createImage(imageName);
            }else {
                //目录存在，直接保存图片
                canCreateImage = createImage(imageName);
            }
            if(canCreateImage) {
                FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean createImage(String destFileName) {
        File file = new File(destFileName);
        if(file.exists()) {
            System.out.println("创建单个文件" + destFileName + "失败，目标文件已存在！");
            return false;
        }
        if (destFileName.endsWith(File.separator)) {
            System.out.println("创建单个文件" + destFileName + "失败，目标文件不能为目录！");
            return false;
        }
        //判断目标文件所在的目录是否存在
        if(!file.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            if(!file.getParentFile().mkdirs()) {
                System.out.println("创建目标文件所在目录失败！");
                return false;
            }
        }
        //创建目标文件
        try {
            if (file.createNewFile()) {
                System.out.println("创建单个文件" + destFileName + "成功！");
                return true;
            } else {
                System.out.println("创建单个文件" + destFileName + "失败！");
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
